// dh-hospital_banners 云对象
// 医院Banner管理

const db = uniCloud.database()
const dbCmd = db.command
const { autoMountHospitalId } = require('dh-common')

module.exports = {
	/**
	 * 获取Banner列表（前台用户）
	 * @param {string} hospitalId - 医院ID
	 * @param {boolean} useCache - 是否使用缓存，默认true
	 */
	async getBannerList(hospitalId, useCache = true) {
		if (!hospitalId) {
			return {
				code: 400,
				message: '医院ID不能为空',
				data: null
			}
		}
		
		try {
			const currentDate = new Date().toISOString().split('T')[0]
			
			// 查询有效的banner
			const res = await db.collection('dh-hospital_banners')
				.where({
					hospital_id: hospitalId,
					status: 1,
					is_orphan: false,
					start_date: dbCmd.lte(currentDate),
					end_date: dbCmd.gte(currentDate)
				})
				.orderBy('sort_order', 'asc')
				.get()
			
			const banners = res.data || []
			
			// 处理banner内容
			const processedBanners = await Promise.all(
				banners.map(async (banner) => {
					try {
						if (banner.content_type === 'custom') {
							// 自定义banner
							return {
								id: banner._id,
								title: banner.title,
								description: banner.description,
								image: this._extractImageUrl(banner.image),
								link: banner.link_url,
								linkType: banner.link_type,
								sortOrder: banner.sort_order
							}
						} else {
							// 引用banner
							if (useCache && banner.cache_strategy === 'cache' && banner.cache_data) {
								// 使用缓存数据
								return {
									id: banner._id,
									title: banner.cache_data.title,
									description: banner.cache_data.description,
									image: banner.cache_data.image,
									link: banner.link_url,
									linkType: banner.link_type,
									sortOrder: banner.sort_order,
									cached: true
								}
							} else {
								// 实时查询
								const content = await this._getReferencedContent(banner)
								if (!content) {
									// 异步标记为孤立
									this._markAsOrphan(banner._id, '关联内容不存在')
									return null
								}
								return {
									id: banner._id,
									title: content.title,
									description: content.description,
									image: content.image,
									link: banner.link_url,
									linkType: banner.link_type,
									sortOrder: banner.sort_order
								}
							}
						}
					} catch (err) {
						console.error('处理banner失败:', banner._id, err)
						return null
					}
				})
			)
			
			// 过滤无效数据
			const validBanners = processedBanners.filter(b => b !== null)
			
			return {
				code: 200,
				message: '获取成功',
				data: validBanners
			}
		} catch (err) {
			console.error('获取Banner列表失败:', err)
			return {
				code: 500,
				message: err.message || '获取失败',
				data: null
			}
		}
	},
	
	/**
	 * 获取Banner列表（管理后台）
	 */
	async getBannerListAdmin({ hospitalId, status, contentType, isOrphan, pageNum = 1, pageSize = 20 }) {
		try {
			const where = {}
			
			if (hospitalId) where.hospital_id = hospitalId
			if (status) where.status = status
			if (contentType) where.content_type = contentType
			if (typeof isOrphan === 'boolean') where.is_orphan = isOrphan
			
			const countRes = await db.collection('dh-hospital_banners')
				.where(where)
				.count()
			
			const total = countRes.total
			
			const res = await db.collection('dh-hospital_banners')
				.where(where)
				.orderBy('sort_order', 'asc')
				.orderBy('create_time', 'desc')
				.skip((pageNum - 1) * pageSize)
				.limit(pageSize)
				.get()
			
			return {
				code: 200,
				message: '获取成功',
				data: {
					list: res.data || [],
					total,
					pageNum,
					pageSize
				}
			}
		} catch (err) {
			console.error('获取Banner列表失败:', err)
			return {
				code: 500,
				message: err.message || '获取失败',
				data: null
			}
		}
	},
	
	/**
	 * 获取Banner详情
	 */
	async getBannerDetail(bannerId) {
		if (!bannerId) {
			return {
				code: 400,
				message: 'Banner ID不能为空',
				data: null
			}
		}
		
		try {
			const res = await db.collection('dh-hospital_banners')
				.doc(bannerId)
				.get()
			
			if (!res.data || res.data.length === 0) {
				return {
					code: 404,
					message: 'Banner不存在',
					data: null
				}
			}
			
			return {
				code: 200,
				message: '获取成功',
				data: res.data[0]
			}
		} catch (err) {
			console.error('获取Banner详情失败:', err)
			return {
				code: 500,
				message: err.message || '获取失败',
				data: null
			}
		}
	},
	
	/**
	 * 创建Banner
	 */
	async createBanner(data) {
		// 验证必填字段
		if (!data.content_type) {
			return { code: 400, message: '内容类型不能为空' }
		}
		
		// 验证自定义banner
		if (data.content_type === 'custom') {
			if (!data.title) {
				return { code: 400, message: '自定义banner标题不能为空' }
			}
		} else {
			// 验证引用banner
			if (!data.content_id) {
				return { code: 400, message: '关联内容ID不能为空' }
			}
		}
		
		try {
			// 准备数据
			let bannerData = {
				content_type: data.content_type,
				content_id: data.content_id || '',
				title: data.title || '',
				description: data.description || '',
				image: data.image || '',
				link_type: data.link_type || 'none',
				link_url: data.link_url || '',
				sort_order: data.sort_order || 100,
				status: data.status || 1,
				start_date: data.start_date || '',
				end_date: data.end_date || '',
				is_orphan: false,
				cache_strategy: data.cache_strategy || 'cache',
				view_count: 0,
				click_count: 0,
				created_by: this.getClientInfo().userInfo?._id || ''
			}
			
			// 🏥 自动挂载医院ID（单一医院系统特性）
			bannerData = await autoMountHospitalId(bannerData)
			
			// 如果是引用类型，立即缓存数据
			if (data.content_type !== 'custom') {
				const tempBanner = {
					content_type: data.content_type,
					content_id: data.content_id
				}
				const cacheData = await this._fetchContentForCache(tempBanner)
				if (cacheData) {
					bannerData.cache_data = {
						...cacheData,
						cached_at: Date.now()
					}
				} else {
					return {
						code: 404,
						message: '关联内容不存在或已禁用'
					}
				}
			}
			
			const res = await db.collection('dh-hospital_banners').add(bannerData)
			
			return {
				code: 201,
				message: '创建成功',
				data: { id: res.id }
			}
		} catch (err) {
			console.error('创建Banner失败:', err)
			return {
				code: 500,
				message: err.message || '创建失败',
				data: null
			}
		}
	},
	
	/**
	 * 更新Banner
	 */
	async updateBanner(bannerId, data) {
		if (!bannerId) {
			return { code: 400, message: 'Banner ID不能为空' }
		}
		
		try {
			// 检查banner是否存在
			const bannerRes = await db.collection('dh-hospital_banners')
				.doc(bannerId)
				.get()
			
			if (!bannerRes.data || bannerRes.data.length === 0) {
				return { code: 404, message: 'Banner不存在' }
			}
			
			const oldBanner = bannerRes.data[0]
			
			// 准备更新数据
			const updateData = {
				update_time: Date.now()
			}
			
			// 允许更新的字段
			const allowedFields = [
				'title', 'description', 'image', 'link_type', 'link_url',
				'sort_order', 'status', 'start_date', 'end_date',
				'cache_strategy', 'content_id'
			]
			
			allowedFields.forEach(field => {
				if (data[field] !== undefined) {
					updateData[field] = data[field]
				}
			})
			
			// 如果更新了content_id，需要重新缓存
			if (data.content_id && data.content_id !== oldBanner.content_id && oldBanner.content_type !== 'custom') {
				const tempBanner = {
					content_type: oldBanner.content_type,
					content_id: data.content_id
				}
				const cacheData = await this._fetchContentForCache(tempBanner)
				if (cacheData) {
					updateData.cache_data = {
						...cacheData,
						cached_at: Date.now()
					}
					updateData.is_orphan = false
					updateData.orphan_reason = ''
				} else {
					return {
						code: 404,
						message: '关联内容不存在或已禁用'
					}
				}
			}
			
			const res = await db.collection('dh-hospital_banners')
				.doc(bannerId)
				.update(updateData)
			
			return {
				code: 200,
				message: '更新成功',
				data: { updated: res.updated }
			}
		} catch (err) {
			console.error('更新Banner失败:', err)
			return {
				code: 500,
				message: err.message || '更新失败',
				data: null
			}
		}
	},
	
	/**
	 * 删除Banner
	 */
	async deleteBanner(bannerId, reason = '') {
		if (!bannerId) {
			return { code: 400, message: 'Banner ID不能为空' }
		}
		
		try {
			const { softDelete } = require('../common/soft-delete-utils')
			const uniIdToken = this.getUniIdToken?.() || this.getClientInfo()?.userInfo
			const userId = uniIdToken?.uid || uniIdToken?._id || ''
			
			const result = await softDelete('dh-hospital_banners', bannerId, userId, reason)
			
			return result
		} catch (err) {
			console.error('删除Banner失败:', err)
			return {
				code: 500,
				message: err.message || '删除失败'
			}
		}
	},
	
	/**
	 * 批量删除Banner
	 */
	async batchDeleteBanners(bannerIds, reason = '') {
		if (!bannerIds || bannerIds.length === 0) {
			return { code: 400, message: 'Banner ID列表不能为空' }
		}
		
		try {
			const { batchSoftDelete } = require('../common/soft-delete-utils')
			const uniIdToken = this.getUniIdToken?.() || this.getClientInfo()?.userInfo
			const userId = uniIdToken?.uid || uniIdToken?._id || ''
			
			const result = await batchSoftDelete('dh-hospital_banners', bannerIds, userId, reason)
			
			return result
		} catch (err) {
			console.error('批量删除Banner失败:', err)
			return {
				code: 500,
				message: err.message || '删除失败'
			}
		}
	},
	
	/**
	 * 记录Banner点击
	 */
	async recordClick(bannerId) {
		if (!bannerId) {
			return { code: 400, message: 'Banner ID不能为空' }
		}
		
		try {
			await db.collection('dh-hospital_banners')
				.doc(bannerId)
				.update({
					click_count: dbCmd.inc(1)
				})
			
			return {
				code: 200,
				message: '记录成功'
			}
		} catch (err) {
			console.error('记录点击失败:', err)
			return {
				code: 500,
				message: err.message || '记录失败'
			}
		}
	},
	
	/**
	 * 记录Banner浏览
	 */
	async recordView(bannerId) {
		if (!bannerId) {
			return { code: 400, message: 'Banner ID不能为空' }
		}
		
		try {
			await db.collection('dh-hospital_banners')
				.doc(bannerId)
				.update({
					view_count: dbCmd.inc(1)
				})
			
			return {
				code: 200,
				message: '记录成功'
			}
		} catch (err) {
			console.error('记录浏览失败:', err)
			return {
				code: 500,
				message: err.message || '记录失败'
			}
		}
	},
	
	// ========== 内部辅助方法 ==========
	
	/**
	 * 获取引用的内容
	 */
	async _getReferencedContent(banner) {
		let collection, fieldMap
		
		switch (banner.content_type) {
			case 'promotion':
				collection = 'dh-hospital_promotions'
				fieldMap = { title: true, description: true, image: true, status: true }
				break
			case 'service':
				collection = 'dh-services'
				fieldMap = { service_name: true, description: true, image: true, status: true }
				break
			case 'product':
				collection = 'dh-products'
				fieldMap = { product_name: true, description: true, image: true, status: true }
				break
			default:
				return null
		}
		
		try {
			const res = await db.collection(collection)
				.doc(banner.content_id)
				.field(fieldMap)
				.get()
			
			const data = res.data?.[0]
			
			if (!data || (data.status && data.status !== 1)) {
				return null
			}
			
			return {
				title: data.title || data.service_name || data.product_name,
				description: data.description || '',
				image: this._extractImageUrl(data.image)
			}
		} catch (err) {
			console.error('获取关联内容失败:', err)
			return null
		}
	},
	
	/**
	 * 标记为孤立banner
	 */
	async _markAsOrphan(bannerId, reason) {
		try {
			await db.collection('dh-hospital_banners')
				.doc(bannerId)
				.update({
					is_orphan: true,
					orphan_reason: reason,
					orphan_check_time: Date.now()
				})
		} catch (err) {
			console.error('标记孤立banner失败:', err)
		}
	},
	
	/**
	 * 获取需要缓存的内容
	 */
	async _fetchContentForCache(banner) {
		let collection, fieldMap
		
		switch (banner.content_type) {
			case 'promotion':
				collection = 'dh-hospital_promotions'
				fieldMap = { 
					title: true, 
					description: true, 
					image: true,
					status: true
				}
				break
			case 'service':
				collection = 'dh-services'
				fieldMap = { 
					service_name: true, 
					description: true, 
					image: true,
					status: true
				}
				break
			case 'product':
				collection = 'dh-products'
				fieldMap = { 
					product_name: true, 
					description: true, 
					image: true,
					status: true
				}
				break
			default:
				return null
		}
		
		try {
			const res = await db.collection(collection)
				.doc(banner.content_id)
				.field(fieldMap)
				.get()
			
			const data = res.data?.[0]
			
			if (!data || (data.status && data.status !== 1)) {
				return null
			}
			
			return {
				title: data.title || data.service_name || data.product_name,
				description: data.description || '',
				image: this._extractImageUrl(data.image),
				source_status: data.status
			}
		} catch (err) {
			console.error('获取内容失败:', err)
			return null
		}
	},
	
	/**
	 * 提取图片URL
	 */
	_extractImageUrl(imageData) {
		if (!imageData) return ''
		if (typeof imageData === 'string') return imageData
		if (typeof imageData === 'object' && imageData.url) return imageData.url
		if (Array.isArray(imageData) && imageData.length > 0) {
			const first = imageData[0]
			return typeof first === 'string' ? first : (first.url || '')
		}
		return ''
	}
}

